from django.db.models import F
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
import random as r
# Create your views here.
from django.urls import reverse

from Manageapp.models import Student, Lesson, Score, Teacher
from Manageapp.stu_content import stu_table


def hello(request):
    return HttpResponse("Hello")


def login(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        level = request.POST.get('level')

        if level == '1':
            try:
                stu = Student.objects.get(s_number=username)
                if str(stu.ID_number) == password:
                    request.session['user_id'] = str(stu.s_number)
                    return render(request, 'student_index.html')
                else:
                    raise Exception("")
            except Exception as e:
                print(e)
                return render(request, 'login.html')
        elif level == '2':
            try:
                tea = Teacher.objects.get(t_number=username)
                if str(tea.t_pass) == password:
                    request.session['user_id'] = str(tea.t_number)
                    return render(request, 'teacher_index.html')
            except Exception as e:
                return render(request, 'login.html')
        elif level == '3':
            if username == 'admin' and password == 'admin':
                return render(request, 'admin_index.html')
            else:
                raise Exception("")
    elif request.method == "GET":
        return render(request, 'login.html')


def get_score(request):
    scores_list = []
    stu = Student.objects.get(s_number=int(request.session.get('user_id')))
    sc = Score.objects.filter(s_number=stu.s_number)
    for s in sc:
        scores = []
        scores.append(stu.s_number)
        scores.append(stu.s_name)
        scores.append(stu.subject)
        scores.append(s.score)
        les = Lesson.objects.get(l_number=s.l_number)
        scores.append(les.l_name)
        tea = Teacher.objects.get(l_number=les.l_number)
        scores.append(tea.t_name)
        if s.score >= 90:
            scores.append("优秀")
        elif s.score >= 80:
            scores.append("良好")
        elif s.score >= 60:
            scores.append("及格")
        else:
            scores.append("不及格")
        scores.append(stu.grade)
        scores_list.append(scores)
        print(scores)
    scoresMap = []
    for s in scores_list:
        score = {
            'id': s[0],
            'name': s[1],
            'subject': s[2],
            'lesson': s[3],
            'score': s[4],
            'teacher': s[5],
            'status': s[6],
            'grade': s[7]
        }
        scoresMap.append(score)
    context = {
        'table': stu_table(),
        'scoresList': scoresMap
    }
    return render(request, 'student_score.html', context=context)



def get_lesson(request):
    stu = Student.objects.get(s_number=int(request.session.get('user_id')))
    sc = Score.objects.filter(s_number=stu.s_number)
    lessMap = []
    for s in sc:
        lessons = []
        lessons.append(stu.subject)
        lessons.append(stu.grade)
        less = Lesson.objects.get(l_number=s.l_number)
        lessons.append(less.l_name)
        lessons.append(less.credit)
        lessons.append(less.time)
        tea = Teacher.objects.get(l_number=less.l_number)
        lessons.append(tea.t_name)
        lessMap.append({
            'subject': lessons[0],
            'grade': lessons[1],
            'lesson': lessons[2],
            'credit': lessons[3],
            'time': lessons[4],
            'teacher': lessons[5],
        })
        print(lessons)
    return render(request, 'student_lesson.html', context={"lessons": lessMap})


def student_index(request):
    stu = Student.objects.get(s_number=int(request.session.get('user_id')))
    return render(request, 'student_index.html', context=locals())


def student_more(request):
    stu = Student.objects.get(s_number=int(request.session.get('user_id')))
    return render(request, 'student_more.html', context=locals())


def update_pwd(request):
    if request.method == "GET":
        flag = request.GET.get('flag')
        request.session['user_flag'] = flag
        return render(request, 'update_password.html', context={'flag': flag})
    elif request.method == "POST":
        try:
            flag = request.session.get('user_flag')
            p1 = request.POST.get('password')
            p2 = request.POST.get('passwords')
            if p1 != p2:
                raise Exception()
            else:
                if flag == '1':
                    stu = Student.objects.get(s_number=int(request.session.get('user_id')))
                    stu.ID_number = p1
                    stu.save()
                elif flag == '2':
                    tea = Teacher.objects.get(t_number=int(request.session.get('user_id')))
                    tea.t_pass = p1
                    tea.save()
                del request.session['user_id']
                del request.session['user_flag']
                return HttpResponseRedirect("/login")
        except Exception as e:
            return render(request, 'update_password.html', context={'msg': '修改失败'})
    return None


def update_pwd_success(request):
    return render(request, 'login.html')


def teacher_index(request):
    tea = Teacher.objects.get(t_number=int(request.session['user_id']))
    less = Lesson.objects.get(l_number=tea.l_number)
    contex = {
        'teacherId': tea.t_number,
        'teacherName': tea.t_name,
        'lesson': less.l_name,
        'credit': less.credit,
        'time': less.time
    }

    return render(request, 'teacher_index.html', context=contex)


def student_info(request):
    status = {}
    students = []
    if request.session['teacher_data']:
        students = request.session['teacher_data']
    else:
        tea = Teacher.objects.get(t_number=int(request.session.get('user_id')))
        scores = Score.objects.filter(l_number=tea.l_number)
        less = Lesson.objects.get(l_number=tea.l_number)
        for s in scores:
            stu = Student.objects.get(s_number=s.s_number)
            if status.get(str(stu.s_number)):
                flage = '已完成'
            else:
                flage = '未录入'
            status[str(stu.s_number)] = flage
            context = {
                'id': stu.s_number,
                'name': stu.s_name,
                'lesson': less.l_name,
                'status': flage
            }
            students.append(context)
        request.session['teacher_data'] = students

    return render(request, 'teacher_info.html', context={"students": students})


def update_score(request):
    sc = request.POST.get('sc')
    stu_id = request.POST.get('stuId')
    lesson = request.POST.get('lessonName')
    print(type(stu_id))
    print(stu_id)
    stu = Student.objects.get(s_number=int(stu_id))
    less = Lesson.objects.get(l_name=lesson)
    scores = Score.objects.get(s_number=stu.s_number, l_number=less.l_number)

    scores.score = int(sc)
    scores.save()
    students = request.session.get('teacher_data')
    for stu in students:
        if stu.get('id') == int(stu_id):
            stu['status'] = '已完成'
            break
        print(stu)
        print(type(stu))
    request.session['teacher_data'] = students
    return render(request, 'teacher_info.html', context={"students": students})


def teacher_score(request):
    id = int(request.session.get('user_id'))
    student_flag_list = get_student_info(id)
    return render(request, 'teacher_scores.html', context={'studnets': student_flag_list})


def get_studet_score(request):
    student_flag_list = []
    flag = request.GET.get('flag')
    id = int(request.session.get('user_id'))
    if flag == '1':
        stu_list = get_student_info(id)
        for s in stu_list:
            if s['status'] == '优秀':
                student_flag_list.append(s)
    elif flag == '2':
        stu_list = get_student_info(id)
        for s in stu_list:
            if s['status'] == '不及格':
                student_flag_list.append(s)
    return render(request, 'teacher_scores.html', context={'studnets': student_flag_list})


def get_student_info(id):
    student_list = []
    tea = Teacher.objects.get(t_number=id)
    less = Lesson.objects.get(l_number=tea.l_number)
    sc = Score.objects.filter(l_number=less.l_number)
    status = ''
    for s in sc:
        if s.score >= 90:
            status = "优秀"
        elif s.score >= 80:
            status = "良好"
        elif s.score >= 60:
            status = "及格"
        else:
            status = "不及格"
        stu = Student.objects.get(s_number=s.s_number)
        stu_info = {
            'id': stu.s_number,
            'name': stu.s_name,
            'grade': stu.grade,
            'lesson': less.l_name,
            'score': s.score,
            'status': status
        }
        student_list.append(stu_info)
    return student_list


def teacher_more(request):
    tea = Teacher.objects.get(t_number=int(request.session['user_id']))

    less = Lesson.objects.get(l_number=tea.l_number)
    contex = {
        'teacherId': tea.t_number,
        'teacherName': tea.t_name,
        'lesson': less.l_name,
        'credit': less.credit,
        'time': less.time
    }
    return render(request, 'teacher_more.html', context=contex)


def admin(request):
    return render(request, 'admin_index.html')


def add_studnet(request):
    if request.method == "GET":
        return render(request, 'add_student.html')
    elif request.method == "POST":
        init_id = 201906001
        username = request.POST.get('username')
        subject = request.POST.get('subject')
        grade = request.POST.get('grade')
        sex = request.POST.get('sex')
        native = request.POST.get('native')
        count = Student.objects.count()
        stu = Student()
        stu.s_number = init_id + count
        stu.s_name = username
        stu.grade = grade
        stu.subject = subject
        if sex == '1':
            stu.sex = '男'
        else:
            stu.sex = '女'
        stu.native_place = native
        stu.ID_number = '111111'
        stu.save()
        return render(request, 'add_student.html', context={'msg': '添加成功'})


def add_lesson(request):
    init_count = 19001
    if request.method == "GET":
        return render(request, 'add_lesson.html')
    elif request.method == "POST":
        count = Lesson.objects.count()
        name = request.POST.get('name')
        credit = request.POST.get('credit')
        time = request.POST.get('time')

        less = Lesson()
        less.l_number = int(init_count) + count
        less.l_name = name
        less.time = int(time)
        less.credit = credit
        less.save()
        return render(request, 'add_lesson.html', context={'msg': '添加成功'})


def add_teacher(request):
    init_count = 2019001
    if request.method == "GET":
        return render(request, 'add_teacher.html')
    elif request.method == "POST":
        msg = ''
        count = Teacher.objects.count()
        teas = Teacher.objects.all()
        lesson_id = request.POST.get('lessonId')
        pwd = request.POST.get('pwd')
        name = request.POST.get('name')

        try:
            less = Lesson.objects.get(l_number=lesson_id)
        except Exception as e:
            msg = '添加课程id不存在'
            return render(request, 'add_teacher.html', context={'msg': msg})
        for t in teas:
            if t.l_number == int(lesson_id):
                return render(request, 'add_teacher.html', context={'msg': '添加课程id不可用'})
            else:
                tea = Teacher()
                tea.t_number = count + int(init_count)
                tea.t_name = name
                tea.pwd = '123'
                tea.l_number = lesson_id
                tea.save()
                return render(request, 'add_teacher.html', context={'msg': '添加成功'})


def out_sys(request):
    del request.session['user_id']
    return HttpResponseRedirect('/')